//
//  KSKARizumuVC.m
//  DashboardHD
//
//  Created by 楊亜玲 on 17/3/29.
//  Copyright © 2017年 Totyu. All rights reserved.
//

#import "KSKARizumuVC.h"
#import "KSKARizumuController.h"

#import "KSKACategory.h"
#import "KSKAAxisView.h"

@interface KSKARizumuVC ()<UICollectionViewDelegate,UICollectionViewDataSource>

/** 顶部显示信息的view */
@property (weak, nonatomic) IBOutlet UIView *topView;
/** 地点和名字 */
@property (weak, nonatomic) IBOutlet UILabel *locationAndNameLabel;
/** 显示本周日期Label */
@property (weak, nonatomic) IBOutlet UILabel *weekDateLabel;


/** 加载了n个子控制器的CollectionView(滑动显示) */
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
/** 横坐标view */
@property (weak, nonatomic) IBOutlet KSKAAxisView *xAxisView;

/** 子控制器数组 */
@property(nonatomic, strong) NSMutableArray *controllerArray;
/** ”周一～周日“ 数组 */
@property(nonatomic, strong) NSMutableArray *weekDateArray;
/** 当前是第几页(0~4) */
@property (nonatomic, assign) int page;

@end

@implementation KSKARizumuVC

static NSString * const reuseIdentifier = @"rizumuVCCell";


- (void)viewDidLoad {
    [super viewDidLoad];
    self.page = 0;
    
    [self setupTopView];
    
    // collectionView定位到最后一个item(主(线程)任务，保证操作在主线程上执行)
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:TotalWeek - self.page - 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
    });
    
    // 注册通知(对应分类的图表显示)
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(categorySelected:) name:@"categorySelected" object:nil];

}


-(void)setupTopView{
    // 0.显示地点和名字
    
    
    // 1.显示今周日期
    self.weekDateLabel.text = [self.weekDateArray objectAtIndex:self.page];
    
    // 2.显示分类信息(自定义KSKACategoryView类)
    
}



/**
 懒加载子控制器
 */
-(NSMutableArray *)controllerArray{
    if (!_controllerArray) {
        _controllerArray = [[NSMutableArray alloc]init];
        for (int i = 0; i<TotalWeek; i++) {
            KSKARizumuController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil]instantiateViewControllerWithIdentifier:@"rizumuChartVC"];
            vc.mondayStr = [self mondayStrWithPage:TotalWeek - i - 1];
            [self addChildViewController:vc];
            [_controllerArray addObject:vc];
        }
    }
    return _controllerArray;
}


/**
 “MM-dd(月)~MM~dd(日)”数组
 */
-(NSMutableArray *)weekDateArray{
    if (!_weekDateArray) {
        NSMutableArray *tmpArr = [NSMutableArray array];
        for (int i = 0; i < TotalWeek; i++) {
            NSDate *date = [NSDate dateWithDaysBeforeNow:i * 7];
            NSString *dateStr = [NSDate dateOfMondayToSundayThisWeekWithDate:date];
            [tmpArr addObject:dateStr];
        }
        self.weekDateArray = tmpArr;
    }
    return _weekDateArray;
}


/** 接收到通知时调用 */

-(void)categorySelected:(NSNotification *)notification{
    KSKLog(@"Kselect:%@",[[notification userInfo]objectForKey:@"actionid"]);
    // 0.清空子控制器数组
    [self.controllerArray  removeAllObjects];
    
    // 1.取得通知传来的useinfo，
    // 如果存在选中的类别
    NSString *actionid = @"";
    NSDictionary *theData = [notification userInfo];
    
    if (theData != nil && [theData objectForKey:@"actionid"]) {
        actionid = [theData objectForKey:@"actionid"];
        
        // 1.2 collectionView重新加载子控制器
        for (int i = 0; i<TotalWeek; i++) {
            KSKARizumuController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil]instantiateViewControllerWithIdentifier:@"rizumuChartVC"];
            vc.mondayStr = [self mondayStrWithPage:TotalWeek - i - 1];
            vc.actionid = [theData objectForKey:@"actionid"];
            [self addChildViewController:vc];
            [_controllerArray addObject:vc];
        }

    }
    
    // 如果不存在选中的类别，显示所有类别图表
    else{
        KSKLog(@"显示所有类别图表 － %@",actionid);
        for (int i = 0; i<TotalWeek; i++) {
            KSKARizumuController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil]instantiateViewControllerWithIdentifier:@"rizumuChartVC"];
            vc.mondayStr = [self mondayStrWithPage:TotalWeek - i - 1];
            [self addChildViewController:vc];
            [_controllerArray addObject:vc];
        }
        
    }
    // 刷新collectionView
    [self.collectionView reloadData];
}



#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    return self.controllerArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    //确保自动适配完毕
    [cell setNeedsLayout];
    [cell layoutIfNeeded];
    
    UIView *subView = [[self.controllerArray objectAtIndex:indexPath.item]view];
    subView.size = cell.size;
    subView.backgroundColor = [UIColor orangeColor];
    [cell.contentView addSubview:subView];
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(self.collectionView.width,self.collectionView.height);
}

#pragma mark - UIScrollViewDelegate

// 滚动视图减速完成，滚动将停止时，调用该方法。一次有效滑动，只执行一次
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    int pageNum = scrollView.contentOffset.x / self.collectionView.width;
    self.page = TotalWeek - pageNum - 1;
    // 1.更新日期
    self.weekDateLabel.text = [self.weekDateArray objectAtIndex:self.page];
    // 2.重新加载控制器数据
    KSKARizumuController *vc = [self.controllerArray objectAtIndex:pageNum];
    vc.mondayStr = [self mondayStrWithPage:self.page];
    KSKLog(@"当前是page %d",self.page);
}


// 获取基准日(所在页面周一的日期)
-(NSString *)mondayStrWithPage:(int)page{
    NSDate *tmp = [NSDate dateWithDaysBeforeNow:page * 7];
    NSString *dateStr = [NSDate dateOfMondayWithDate:tmp];
    return dateStr;
}

/** 移除通知 */
-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
